<?php
namespace app\agent\controller;
use think\Controller;
use think\Db;
use app\common\controller\AgentBaseController;

class Count extends AgentBaseController
{
	//统计
	public function user_form()
    {
    	$usersum = db('info_user')->where('mobile','<>','')->where('level',session('agent_user_id'))->count();
    	$this->assign('usersum',$usersum);
    	$usersum1 = db('info_user')->where('mobile','eq','')->where('level',session('agent_user_id'))->count();
    	$this->assign('usersum1',$usersum1);
    	return $this->fetch();
    }
    
	public function goods_form(){
		$this->assign('goods_list','');
		//获取门店ID
		$agent_store = db('agent_store')->where('agent_id',session('agent_id'))->select();
		$this->assign('agent_store',$agent_store);		
		//获取商品分类类型
		$goods_type = db('agent_type')->where('agent_id',session('agent_id'))->select();
		$this->assign('goods_type',$goods_type);
		$this->assign('empty','<span class="empty">没有数据</span>');
		
    	return $this->fetch();
	}
    
    public function goods_list()
    {
		if(!empty(input('goods_no')))$where['g.goods_no'] = ['like','%'.input('goods_no').'%'];
		
		if(!empty(input('goods_name')))$where['g.goods_name'] = ['like','%'.input('goods_name').'%'];
		
		if(!empty(input('type_id')))$where['g.trade_id'] = input('type_id');
		if(!empty(input('begin_time')) && !empty(input('end_time'))){ 
			$where['m.pay_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}
		
	
		
		$this->assign('begin_time',input('begin_time'));		
		$this->assign('end_time',input('end_time'));	
		$this->assign('goods_name',input('goods_name'));		
		$this->assign('goods_no',input('goods_no'));		
		$where['g.agent_id'] = session('agent_id'); 
		$f['state'] = 2;
		$f['order_type'] =7;
		$f['agent_id'] = session('agent_id'); 
		$field="sum(m.origin_price) as price,sum(m.member_score) as dk";
		$goods_list = db('agent_goods')
						->alias('g')
						->field("g.id as goods_id,g.goods_no,g.stock,g.goods_name,g.sales,$field")
						->join("log_paylog_copy m",'g.id = m.goods_id','LEFT')
						->group('g.id')
						->where($where)
						->paginate(10,false,['query'=>request()->param()]);
		$this->assign('goods_list',$goods_list);

		//获取商品分类类型
		$goods_type = db('agent_type')->where('agent_id',session('agent_id'))->select();
		$this->assign('goods_type',$goods_type);
		$this->assign('empty','<span class="empty">没有数据</span>');
		
    	return $this->fetch();
    }
    
    public function summary()
    {
    	$agent_id=session("agent_id");	
    	$where['agent_id']=session("agent_id");	
		$where1['agent_id']=session("agent_id");
		$mems=db('info_user')->where("tj_agent",$agent_id)->count();
		$today_users=db("info_user")->where("tj_agent",$agent_id)->whereTime('add_time', 'today')->cache(60)->count();
	   	$week_users=db("info_user")->where("tj_agent",$agent_id)->whereTime('add_time', 'week')->cache(60)->count();
	   	$month_users=db("info_user")->where("tj_agent",$agent_id)->whereTime('add_time', 'month')->cache(60)->count();
	    $this->assign('today_mems',$today_users?$today_users:0);
		$this->assign('week_mems',$week_users?$week_users:0);
		$this->assign('month_mems',$month_users?$month_users:0);
		$this->assign('mems',$mems?$mems:0);
		
		$list=db("log_paylog_copy")->where($where)->field("uid,balance,order_type,score,sy_type,payment_type")->select();
		$logs=db('log_paylog_copy')->where($where)->cache(30)->sum("balance");	   
	   	$today_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   	$week_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'week')->cache(30)->sum("balance");
	   	$month_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'month')->cache(30)->sum("balance");
	   	$this->assign("logs",$logs?$logs:0);
	   	$this->assign("today_logs",$today_logs?$today_logs:0);
	   	$this->assign("week_logs",$week_logs?$week_logs:0);
	   	$this->assign("month_logs",$month_logs?$month_logs:0);

		$bishu_where['order_type'] = ['not in','3,4,5'];
		$bishu_where['state'] = 2;
		$bishu_where['agent_id'] = session("agent_id");
		$counts=db('log_paylog')->where($bishu_where)->cache(30)->count();
	    $today_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'today')->cache(30)->count();
	   	$week_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'week')->cache(30)->count();
	   	$month_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'month')->cache(30)->count();
	   	$this->assign("counts",$counts?$counts:0);
	   	$this->assign("today_counts",$today_counts?$today_counts:0);
	   	$this->assign("week_counts",$week_counts?$week_counts:0);
	   	$this->assign("month_counts",$month_counts?$month_counts:0);
		
		$where['balance']=['<',0];
		$where['order_type']=['in','1,3,7'];
	    $today_scores=db("log_agent_score")->where($where)->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   	$week_scores=db("log_agent_score")->where($where)->whereTime('add_time', 'week')->cache(30)->sum("balance");
	   	$month_scores=db("log_agent_score")->where($where)->whereTime('add_time', 'month')->cache(30)->sum("balance");
	   	$total_scores=db("log_agent_score")->where($where)->cache(30)->sum("balance");
		
		$where1['balance']=['>',0];
		$where1['order_type']=['in','1,3,7'];
	    $today_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   	$week_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'week')->cache(30)->sum("balance");
	   	$month_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'month')->cache(30)->sum("balance");
	   	$total_scores1=db("log_agent_score")->where($where1)->cache(30)->sum("balance");
	   	$this->assign("today_scores",$today_scores?$today_scores:0);
	   	$this->assign("week_scores",$week_scores?$week_scores:0);
	   	$this->assign("month_scores",$month_scores?$month_scores:0);
		$this->assign("total_scores",$total_scores?$total_scores:0);
		$this->assign("today_scores1",$today_scores1?$today_scores1:0);
	   	$this->assign("week_scores1",$week_scores1?$week_scores1:0);
	   	$this->assign("month_scores1",$month_scores1?$month_scores1:0);
		$this->assign("total_scores1",$total_scores1?$total_scores1:0);
		
		$cz_where['a.order_type'] = 8;
		$cz_where['a.state'] = 2;
		$cz_where['a.tj_agent_id'] = session("agent_id");
		$today_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')	
							->where($cz_where)
							->whereTime('a.add_time', 'today')
							->select();	
								
		$week_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->whereTime('a.add_time', 'week')
							->select();		
		
		$month_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->whereTime('a.add_time', 'month')
							->select();		
							
		$all_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->select();						
		
		$cz_info['today_total_cz'] 	= $today_total_cz[0]['balance'];
		$cz_info['week_total_cz'] 	= $week_total_cz[0]['balance'];
		$cz_info['month_total_cz'] 	= $month_total_cz[0]['balance'];
		$cz_info['all_total_cz'] 	= $all_total_cz[0]['balance'];
		$this->assign("cz_info",$cz_info);
    	return $this->fetch();
    }
        public function detailed()
    {
		if(input('begin_time') && input('end_time')){
			$where['a.add_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}
		if(input('store_name'))$where['a.chain_id'] = input('store_name');
		if(input('syylist'))$where['a.clerk_id'] = input('syylist');
		if(input('pay_type'))$where['a.pay_type'] = input('pay_type');
		$where['a.state'] = 2;
		if(input('order_sn'))$where['a.order_sn'] = ['like','%'.input('order_sn').'%'];

    	$where['a.agent_id|tj_agent_id'] = session('agent_id');	
		
		if(input('order_type')){
			if(input('order_type')==6){
				$where['a.order_type'] = ['in','6,7'];
			}else{
				$where['a.order_type']=['in',"input('order_type')"];
			}
		}else{
			$where['a.order_type'] = ['not in','3,4,5,8'];	
		}	
		
    	$paylog = db('log_paylog')
    	->alias('a')
    	->field('a.*,w.store_name,c.goods_name,sy.name as sy_name')
		->join('agent_store w','a.agent_id = w.agent_id and a.chain_id = w.id','left')
		->join('agent_goods c','a.goods_id = c.id','left')
		->join('agent_clerk sy','a.clerk_id = sy.id','left')
    	->where($where)
		->order('a.add_time desc')
    	->paginate(10,false,['query'=>request()->param()]);
    	
		$this->assign('paylog',$paylog);
		$this->assign('end_time',input('end_time'));
		$this->assign('begin_time',input('begin_time'));

		$and_w['a.order_type'] = ['not in','11'];	 //会员卡消费不计算
		//消费金额
		$xfprice = db('log_paylog_copy')->alias('a')->where($where)->where($and_w)->sum('a.origin_price');
		$this->assign('xfprice',$xfprice);
		
		//实际金额
		$sjprice = db('log_paylog_copy')->alias('a')->where($where)->where($and_w)->sum('a.balance');
		$this->assign('sjprice',$sjprice);
		
		//赠送
		$zsscore = db('log_paylog_copy')->alias('a')->where($where)->where($and_w)->where("a.payment_type=1 or member_score>0")->sum('a.member_score');
		$this->assign('zsscore',$zsscore);
		
		//抵扣
		$dkscore = db('log_paylog_copy')->alias('a')->where($where)->where($and_w)->where("a.payment_type=2 or member_score<0")->sum('a.member_score');
		$this->assign('dkscore',$dkscore);
		
		
		//获取收银员
		$clerk_list = db('agent_clerk')->where('agent_id',session('agent_id'))->select();
		$this->assign('clerk_list',$clerk_list);
		$this->assign('empty','<span class="empty">没有数据</span>');
		
    	return $this->fetch();
    }

 	//明细导出
    public function detail_dc(){
		if(input('begin_time') && input('end_time')){
			$where['a.add_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}
		
		if(input('syylist'))$where['a.clerk_id'] = input('syylist');
		if(input('pay_type'))$where['a.pay_type'] = input('pay_type');
		if(input('sy_type'))$where['a.sy_type'] = input('sy_type');
		if(input('state')){
			$where['a.state'] = input('state');
		}else{
			$where['a.state'] = 2;
		}
		if(input('order_sn'))$where['a.order_sn'] = ['like','%'.input('order_sn').'%'];

    	$where['a.agent_id|tj_agent_id'] = session('agent_id');		
		if(input('order_type')){
			if(input('order_type')==6){
				$where['a.order_type'] = ['in','6,7'];
			}else{
				$where['a.order_type']=input('order_type');
			}
		}else{
			$where['a.order_type'] = ['not in','3,4,5'];	
		}
		
    	$list = db('log_paylog')
    	->alias('a')
		->field('a.*,sy.name as sy_name')
		->join('agent_clerk sy','a.clerk_id = sy.id','left')
    	->where($where)
		->order('a.add_time desc')
    	->select();

    	
		$str ="订单号,订单类型,会员编号,交易金额,实际金额,抵扣,日期"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($list as $k=>$row){
        	$order_sn = iconv('utf-8','gbk',$row['order_sn'].'	');
        	$order_type = iconv('utf-8','gbk',log_type_msg($row['order_type']));
        	$sy_name = iconv('utf-8','gbk',$row['sy_name']); 
			$uid = iconv('utf-8','gbk',$row['uid'].'	');
			
			if($row['pay_type']==1){
				$payname = '余额';
			}elseif($row['pay_type']==2) {
				$payname = '微信';
			}elseif($row['pay_type']==3) {
				$payname = '支付宝';
			}else{
				$payname = '银联';
			}
			$pay_type = iconv('utf-8','gbk',$payname);
			$xfprice = iconv('utf-8','gbk','	'.$row['origin_price']);
			$sjprice = iconv('utf-8','gbk','	'.$row['balance']);		
//			$give_score = iconv('utf-8','gbk','	'.$row['payment_type']==1?$row['member_score']:($row['member_score']>0)?$row['member_score']:'0.00');
			$deduction_score = iconv('utf-8','gbk','	'.$row['payment_type']==2?$row['member_score']:($row['member_score']<0)?$row['member_score']:'0.00');
			$add_time = iconv('utf-8','gbk',$row['add_time'].'	');
			$str .= $order_sn.",".$order_type.",".$uid.",".$xfprice.",".$sjprice.",".$deduction_score.",".$add_time.","."\n"; //用引文逗号分开 
        } 

	  	$filename ='明细列表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}

    public function syylist()
    {
    	//获取收银员
		$data = db('agent_clerk')->where('chain_id',input('id'))->select();
		return json(["data"=>$data]);
    }
    
 	//导出
    public function detail_spdc(){   
		if(!empty(input('goods_no')))$where['g.goods_no'] = ['like','%'.input('goods_no').'%'];
		
		if(!empty(input('goods_name')))$where['g.goods_name'] = ['like','%'.input('goods_name').'%'];
		
		if(!empty(input('type_id')))$where['g.trade_id'] = input('type_id');
		if(!empty(input('begin_time')) && !empty(input('end_time'))){ 
			$where['m.pay_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}
		
	
		
		$this->assign('begin_time',input('begin_time'));		
		$this->assign('end_time',input('end_time'));	
		$this->assign('goods_name',input('goods_name'));		
		$this->assign('goods_no',input('goods_no'));		
		$where['g.agent_id'] = session('agent_id'); 
		$f['state'] = 2;
		$f['order_type'] =7;
		$f['agent_id'] = session('agent_id'); 
		$field="sum(m.origin_price) as price,sum(m.member_score) as dk";
		$goods_list = db('agent_goods')
						->alias('g')
						->field("g.id as goods_id,g.goods_no,g.stock,g.goods_name,g.sales,$field")
						->join("log_paylog_copy m",'g.id = m.goods_id','RIGHT')
						->group('g.id')
						->where($where)
						->select();

		$str ="商品编号,商品名称,销量,金额,抵扣鼓励金,库存"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($goods_list as $k=>$row){ 
        	$goods_no = iconv('utf-8','gbk',$row['goods_no'].'	');
			$goods_name = iconv('utf-8','gbk',$row['goods_name']); 
			$sales = iconv('utf-8','gbk',$row['sales']); 
			$pay_price = iconv('utf-8','gbk', $row['price']?$row['price']:0); 
			$total_dk_price = iconv('utf-8','gbk',$row['dk']);
			$stock = iconv('utf-8','gbk',$row['stock']);

			$str .= $goods_no.",".$goods_name.','.$sales.','.$pay_price.
			",".$total_dk_price.",".$stock.","."\n"; //用引文逗号分开 
        } 

	  	$filename ='明细列表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}   
	
	//明细导出
	public function detail_mxdc(){   
		if(input('goods_no'))$where['g.goods_no'] = ['like','%'.input('goods_no').'%'];
		
		if(input('goods_name'))$where['g.goods_name'] = ['like','%'.input('goods_name').'%'];
		
		if(input('type_id'))$where['g.trade_id'] = input('type_id');
		if(input('begin_time') && !empty(input('end_time'))){
			$map['a.add_time'] = ['between time',[input('begin_time'),input('end_time')]];
			$dw['f.add_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}
		
		$order = 'b.add_time desc';
		if(input('order') == 'total_money'){
			$order = 'b.total_pay desc';
		}
		if(input('order') == 'total_num'){
			$order = 'g.sales desc';
		}
		
		$where['g.agent_id'] = session('agent_id');
		$where['g.goods_state'] = 2;	
		$map['a.status'] = ['in',[2,5]];
		$map['a.agent_id'] = session('agent_id');
		
		//获取当前店铺商品
		$order_list = db('agent_syorder')
						->alias('a')
						->field('sn,pay_type,sum(b.num*b.price) total_pay,b.goods_id,sum(b.price) as total_money,sum(b.num) as sales,sum(b.dk_price) as dk_price,sum(b.zs_price) as zs_price,a.add_time')
						->join('agent_syorder_items b','a.id = b.order_id','LEFT')			
						->where($map)
						->group('b.goods_id')
						->buildSql();

		$d = db('agent_syorder_items')->group("goods_id")->buildSql();
		
		$goods_list = db('agent_goods')
						->alias('g')
						->field("d.price,b.sn,b.total_money,b.pay_type,g.id as goods_id,g.goods_no,g.stock,g.goods_name,g.sales,c.type_name,b.dk_price as total_dk_price,b.zs_price as total_zs_price,b.add_time,b.total_pay")
						->join($order_list.' b','g.id = b.goods_id','LEFT')
						->join('agent_type c','g.trade_id = c.id','LEFT')
						->join($d.'d','d.goods_id = g.id','LEFT')
						->where($where)
						->order($order)
						->select();
		
		$str ="订单号,商品编号,商品名称,销售数量,商品单价,交易类型,总价,抵扣鼓励金,销售日期"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($goods_list as $k=>$row){
        	$sn = iconv('utf-8','gbk',$row['sn'].'	');
        	$goods_id = iconv('utf-8','gbk',$row['goods_no'].'	');
			$name = iconv('utf-8','gbk',$row['goods_name']);
			$num = iconv('utf-8','gbk',$row['sales']);
			$price = iconv('utf-8','gbk',$row['price']);
			
			if($row['pay_type']==1){
				$payname = '现金';
			}elseif($row['pay_type']==2) {
				$payname = '微信';
			}elseif($row['pay_type']==3) {
				$payname = '支付宝';
			}else{
				$payname = '银联';
			}
			$pay_type = iconv('utf-8','gbk',$payname);
			
			$total_price = iconv('utf-8','gbk',$row['sales']*$row['price']);
			$zs_price = iconv('utf-8','gbk',$row['total_zs_price']);
			$dk_price = iconv('utf-8','gbk',$row['total_dk_price']);
			$add_time = iconv('utf-8','gbk',$row['add_time'].'	');
			
			$str .= $sn.",".$goods_id.",".$name.",".$num.",".$price.",".$pay_type.','.$total_price.
			",".$dk_price.",".$add_time.","."\n"; //用引文逗号分开 
        } 

	  	$filename ='销售明细列表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;  
    }
    
	//购买电子劵 
	public function  buy_dzj(){
		if(input('begin_time') && input('end_time')){
			$where['a.add_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}

    	$where['a.agent_id|tj_agent_id'] = session('agent_id');	
		
		$where['a.order_type']= 8; //购买电子劵
		
    	$paylog = db('log_paylog_copy')
    	->alias('a')
    	->field('a.*,w.store_name,c.goods_name')
		->join('agent_store w','a.agent_id = w.agent_id and a.chain_id = w.id','left')
		->join('agent_goods c','a.goods_id = c.id','left')
    	->where($where)
		->order('a.add_time desc')
    	->paginate(10,false,['query'=>request()->param()]);
    	
		$this->assign('paylog',$paylog);
		$this->assign('end_time',input('end_time'));
		$this->assign('begin_time',input('begin_time'));

		//消费金额
		$xfprice = db('log_paylog_copy')->alias('a')->where($where)->sum('a.origin_price');
		$this->assign('xfprice',$xfprice);
		
		//实际金额
		$sjprice = db('log_paylog_copy')->alias('a')->where($where)->sum('a.balance');
		$this->assign('sjprice',$sjprice);
		
		//总分佣
		$count_maid = db('log_paylog_copy')->alias('a')->where($where)->sum('a.tj_agent_commission');	
		$this->assign('count_maid',$count_maid);	
		
		$this->assign('empty','<span class="empty">没有数据</span>');
		return $this->fetch();
	}
	
	//导出
	public function buy_export(){
		if(input('begin_time') && input('end_time')){
			$where['a.add_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}
   		$where['a.agent_id|tj_agent_id'] = session('agent_id');	
		$where['a.order_type']= 8; //购买电子劵	
		
    	$list = db('log_paylog')
    	->alias('a')
		->field('a.*')
    	->where($where)
		->order('a.add_time desc')
    	->select();
		$str ="订单号,会员编号,电子劵面额,商家分佣,收银员id,收银员分佣,推荐人分佣,日期"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($list as $k=>$row){
        	$order_sn = iconv('utf-8','gbk',$row['order_sn'].'	');
			$uid = iconv('utf-8','gbk',$row['uid'].'	');
			$balance = iconv('utf-8','gbk',$row['balance']*10 .'	'); 
			$tj_agent_commission = iconv('utf-8','gbk','	'.$row['tj_agent_commission']);
			$tj_clerk_id = iconv('utf-8','gbk','	'.$row['tj_clerk_id']);		
			$clerk_commission = iconv('utf-8','gbk','	'.$row['clerk_commission']);		
//			$pt_commission = iconv('utf-8','gbk','	'.$row['pt_commission']);		
			$level1_commisssion = iconv('utf-8','gbk','	'.$row['level1_commisssion']);
			$add_time = iconv('utf-8','gbk','	'.$row['add_time']);
			$str .= $order_sn.",".$uid.",".$balance.",".$tj_agent_commission.",".$tj_clerk_id.",".$clerk_commission.",".$level1_commisssion.",".$add_time.","."\n"; //用引文逗号分开 
        } 

	  	$filename ='购买电子劵列表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}
}
